package com.wtx.security.config;

import com.wtx.security.service.SysMenuService;
import com.wtx.security.vo.SysMenuVO;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Component
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    private SysMenuService sysMenuService;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestURI =
                ((FilterInvocation) object).getRequest().getRequestURI();
        List<SysMenuVO> allMenu = sysMenuService.getAllMenu();
        for (SysMenuVO menu : allMenu) {
            if (antPathMatcher.match(menu.getPermissionUrl(), requestURI)) {
//                String[] roles = menu.getRoles().stream()
//                        .map(r -> r.getName()).toArray(String[]::new);
                return SecurityConfig.createList(menu.getPermissionUrl());
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");//请求的url在数据库表中不存在相应模式，就假设该请求登录即可访问，直接返回 ROLE_LOGIN
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
